<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="router">

    </div>
    <script>
        const oRouter = document.getElementById('router');
        const treeData = [
            {
                id: 1,
                name: '一级1',
                pId: 0
            },
            {
                id: 2,
                name: '一级2',
                pId: 0
            },
            {
                id: 3,
                name: '一级3',
                pId: 0
            },
            {
                id: 4,
                name: '一级1-二级1',
                pId: 1
            },
            {
                id: 5,
                name: '一级1-二级1-三级1',
                pId: 4
            },
            {
                id: 6,
                name: '一级2-二级1',
                pId: 2
            },
            {
                id: 7,
                name: '一级3-二级1',
                pId: 3
            },
        ];
        function formatRouterTree(data) {
            let parents = data.filter(p => p.pId === 0),
                children = data.filter(p => p.pId !== 0);
            dataToTree(parents, children);
            function dataToTree(parents, children) {
                parents.map((p) => {
                    children.map((c, i) => {
                        if (c.pId === p.id) {
                            let _c = JSON.parse(JSON.stringify(children));
                            _c.splice(i, 1);
                            dataToTree([c], _c);

                            if (p.children) {
                                p.children.push(c);
                            } else {
                                p.children = [c]
                            }
                        }
                    })
                })
            }
            return parents;
        }
        let data = formatRouterTree(treeData);
        renderTree(data);
        function renderTree(data) {
            for (let i of data) {
                const oList = document.createElement('div');
                oList.innerHTML = i.name;
                oRouter.appendChild(oList)
                if (i.children) {
                    renderTree(i.children)
                }
            }
        }
    </script>
</body>

</html>